process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true' // 警告压制
process.env.DIST = path.join(__dirname, '../../dist')
process.env.VITE_PUBLIC = app.isPackaged ? process.env.DIST : path.join(process.env.DIST, '../../pica/public')

import path from 'path'
import { app, ipcMain, BrowserWindow,shell,Tray, Menu,screen  } from 'electron'
import { Sql, initWithIpc as initSql, initDatabase,update_ste,initdownload } from './sqlite3'
import { IPC } from 'root/common/constants'

 
 
let window: BrowserWindow | null
let sql: Sql | null
let win : BrowserWindow 
let win2 : BrowserWindow | null

function createWindow() {
   win = new BrowserWindow({
    icon: path.join(process.env.VITE_PUBLIC, 'fav.png'),
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js'),
      contextIsolation: false,// 允许 Ajax 跨域
      webSecurity: false,
      partition: 'persist:derp',
      nodeIntegration: true, // 启用Node integration
      webviewTag: true, // 允许在页面内使用webview标签
      nodeIntegrationInWorker: true, // 在Web工作器中启用了Node集成
      // 允许在子页面(iframe)或子窗口(child window)中集成Node.js
      nodeIntegrationInSubFrames: true,
      
            
      // partition: String(+new Date())//C:\Users\yanjin\AppData\Roaming清除缓存
    },
    // x:10,
    //y:30,
    frame: false,
    
    //titleBarStyle: 'hiddenInset',
    //resizable:false,
    //transparent: true,
    show:false,
    width: 1000,
    height: 650
  })
  //console.log(process.versions['chrome'],"chrome版本");
 
  win.loadFile(path.join(process.env.VITE_PUBLIC, 'loading.html'))
  const tray = new Tray(path.join(process.env.VITE_PUBLIC, 'github.png'));
  const trayContextMenu = Menu.buildFromTemplate([
      {
          label: '打开',
          click: () => {
            win.show();
          }
      }, {
          label: '退出',
          click: () => {
              app.exit()
          }
      }
  ]);
  //托盘
  tray.setToolTip('COSCK');
  tray.on('click', () => {
    win.show();
  });
  tray.on('right-click', () => {
      tray.popUpContextMenu(trayContextMenu);
  });
  win.once("ready-to-show", () => {
    win.show()
    if (process.env.VITE_DEV_SERVER_URL) {
      win.loadURL(process.env.VITE_DEV_SERVER_URL)
      win.webContents.openDevTools() // 开发期自动打开开发者工具
    } else {
      win.loadFile(path.join(process.env.DIST, 'index.html'))
    } 
  });
  win.setPosition(win.getPosition()[0],150,true)
  return win
}

// 鼠标点击任务栏的应用图标触发
app.on('activate', () => {
  const allWindows = BrowserWindow.getAllWindows()
  if (allWindows.length) {
    allWindows[0].focus()
  } else {
    createWindow()
  }
})

app.on('window-all-closed', () => {
  window = null
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('quit', () => {
  sql?.database.close()
  sql = null
})

app.whenReady().then(async () => {
  // 创建窗口
  window = createWindow()
  sql =  initSql(window)
  initDatabase()
  initdownload()
  // app.dock.hide();
 
  //下载
  ipcMain.handle(IPC.ELECTRON_DOWNLOAD, (event,url,size,name,down_id) => {
      let value = 0
      window?.webContents.downloadURL(url)// 监听 will-download
      window?.webContents.session.once('will-download', (e, item) => {
        const filePath = path.join(app.getAppPath(), '/download', item.getFilename())
        item.setSavePath(filePath) 
        //监听下载过程，计算并设置进度条进度
        item.on('updated', (evt, state) => {
          if ('progressing' === state) {
            if (item.isPaused()) { // 下载停止
            }else{
              if (item.getReceivedBytes() && size) {
                value = Math.ceil(100 * (item.getReceivedBytes() / size))
              }
              let upload = {
                name:name,
                size:size,
                value:value
              }
              update_ste(down_id,upload.value)
              //window?.webContents.send('uploadProgress'+down_id,upload)//此处多线程采用数据库方法，不单线监听
              window?.setProgressBar(value)
            }
            
          }
        })
        //监听下载结束事件
        item.once('done', (e, state) => {
          //如果窗口还在的话，去掉进度条
          if (!window?.isDestroyed()) {
            window?.setProgressBar(-1)
          }
          // 下载成功后打开文件所在文件夹
          // if (state === 'completed') {
          //   setTimeout(() => {
          //     shell.showItemInFolder(filePath)
          //   }, 1000)
          // }
        })
      })
      return "下载:"+name;
  })

  //打开文件夹
  ipcMain.handle(IPC.ELECTRON_OPENDIR, (event) => {
    const filePath = path.join(app.getAppPath(), '/download/')
    shell.showItemInFolder(filePath)
  })

  //打开新窗口
  ipcMain.handle(IPC.ELECTRON_OPENWIN, (event,url,w,h,type) => {
    const width = window?.getSize()[0] || 0;
    let left = window?.getPosition()[0]|| 0;
    let top = window?.getPosition()[1]|| 0;
    if(type==1){
      left = left+width/2-w/2
      top  = top+20
      //left = screen.getPrimaryDisplay().workAreaSize.width-w-5
    }else{
      left = left-5+20
      top  = top+20
    }
    if(win2){
      if (process.env.VITE_DEV_SERVER_URL) {
        win2?.loadURL(process.env.VITE_DEV_SERVER_URL+"/#"+url);
      } else {
        win2?.loadFile(path.join(process.env.DIST, 'index.html'), {
            hash: url
        })
      }
      win2?.setContentSize(330, 60,true)
      win2?.webContents.focus()
      return
    }
    
     win2 = new BrowserWindow({
        width:w,
        height:h,
        x:left,
        y:top,
        frame: false,
        show:false,
        resizable:false,
        //transparent: true,
        //icon: path.join(process.env.VITE_PUBLIC, 'fav.ico'),
        
        webPreferences: {
          preload: path.join(__dirname, '../preload/index.js'),
          nodeIntegration: true, // 启用Node integration
          webSecurity: false,
          partition: 'persist:derp',
          webviewTag: true, // 允许在页面内使用webview标签
          contextIsolation: false, // 设置此项为false后，才可在渲染进程中使用electron api
        },
    })
    win2.loadFile(path.join(process.env.VITE_PUBLIC, 'loading.html'))
    win2.setMenu(null);
    win2.once("ready-to-show", () => {
      win2?.show()
      if(type==1){
        if (process.env.VITE_DEV_SERVER_URL) {
          win2?.loadURL(process.env.VITE_DEV_SERVER_URL+"/#"+url);
        } else {
          win2?.loadFile(path.join(process.env.DIST, 'index.html'), {
              hash: url
          })
        }
      }else{
        win2?.loadURL(url);
      }
    });
    win2.setPosition(win2.getPosition()[0],70,true)
    win2.setAlwaysOnTop(true);
    win2?.webContents.focus()
    //win2.webContents.openDevTools() // 开发期自动打开开发者工具
    //test页面路由
  })

 

  // 下面是写的关闭、最小化、最大化窗口抛出事件，在vue/ layouts/index.vue使用了
  ipcMain.handle(IPC.ELECTRON_WINDOWS, (event, params) => {
    const size = window?.getSize();
    const width = size?.[0] || 0;

    if(params==='minimize'){
      window?.minimize()
    } else if(params==='maximize'){
      // if(width < 1201){
      //   window?.maximize()
      // }else{
      //   window?.unmaximize();
      // }
      if (width > 1201) {
        window?.unmaximize();
      } else {
        window?.maximize();
      }
    }else if(params==='close'){
      window?.close()
      window = null
      app.exit()
    }else if(params==='top'){
      window?.setAlwaysOnTop(true);
    }else if(params==='notop'){
      window?.setAlwaysOnTop(false);
    }else if(params==='max'){
      window?.maximize();
    }else if(params==='unmax'){
      window?.unmaximize();
    }else if(params==='close_small'){
      win2?.close();
      win2 = null
    }else if(params==='small_down'){
      //win2?.setMinimumSize(330, 250)
      win2?.setContentSize(330, 250,true)
    }else if(params==='small_up'){
      win2?.setContentSize(330, 60,true)
    }else if(params==='clear'){
      win?.webContents.session.clearCache();
    }
    return width;
  })



})
